package com.example.controller;

import com.example.entity.Student;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/hello")
public class HelloController  {

    public HelloController(){
        System.out.println("HelloController..构造函数");
    }

    @Autowired
    private StudentService studentService;

    @RequestMapping("/hello")
    public String a(HttpServletRequest request, HttpSession session) {

        return "hello";
    }

    @RequestMapping("/show")
    public ModelAndView doShow(String account){
        if(account == null){
            throw new RuntimeException("非法访问/show接口");
        }else if(account.length()==0 || account.length()>10){
            throw new RuntimeException("account长度不符合要求");
        }
        ModelAndView mv = new ModelAndView("show");
        System.out.println("接收到account:"+account);
        mv.addObject("account",account);
        return mv;
    }

    @RequestMapping("/hello2")
    public ModelAndView b() {
        System.out.println("SpringMVC框架搭建成功");

        List<String> names = studentService.getAll2();

        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("names",names);
        return modelAndView;
    }


    @GetMapping("/date")
    @ResponseBody
    public Object helloDate(java.util.Date date){
        System.out.println(date);
        HashMap<String,Object> map = new HashMap<>();
        map.put("date",date);
        return map;
    }

    @GetMapping("/student")
    @ResponseBody
    public Object helloStudent(Student student){
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",student);
        return map;
    }

//    @InitBinder
//    public void initBinder(WebDataBinder dataBinder){
//        dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
//    }
}
